from boe2.reddit import * 
import getpass

commentindex = 0
currentsub = None
sublist = {}
reddit = client.client()
show_comment_id = True

def listhelp():
    print('\t- help : print this message')
    print('\t- reddit <subreddit> : list subreddit content')
    print('\t- article <article ID> : list content and comments of selected article')
    print('\t- save <filename>(optional) : save current article and it\'s comments')
    print('\t- login <username> <password>(optional): authenticate as the given username')
    print('\t- self : show statistics about the logged in user')
    print('\t- reply <parentID> <response> : reply to an article/comment. If no parentID is given, post a comment the article root')

def listsub(input):
    sublist.clear()
    threads = reddit.getSubReddit(input)
    for i in range(0,len(threads.data)):
           sublist[str(i)] = threads.data[i]
           print("({0}) - {1} ({2})".format(i, sublist[str(i)].title, sublist[str(i)].author))

def selectthread(input):
    global currentsub
    if sublist[input] is None:
        print("Invalid sub selected.")
        return
    currentsub = sublist[input]
    print("+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+")
    if currentsub.selftext is not None and currentsub.selftext is not '':
        print(currentsub.selftext)
    else:
        print(currentsub.url)
    print("+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+")
    commentlist = reddit.getComments(currentsub.permalink)
    printComments(lambda x: print(x), commentlist, 0)

def printComments(write, listing, level):
    for comment in listing:
        if show_comment_id:	
            write("--" * level + "[{0}]<{1}> ".format(comment.id, comment.author) + comment.body)
        else:
            write("--" * level + "<{0}> ".format(comment.author) + comment.body)
        printComments(write, comment.replies, level + 1)
        if level == 0:
            write("========================================")
			
def savecomments(filename):
	if currentsub == None:
		print("No article selected. Nothing has been saved.")
		return
	if(len(filename) == 0):
		filename = "".join([c for c in currentsub.title if c.isalpha() or c.isdigit() or c==' ']).rstrip().lower().replace(' ', '_')
	f = open(filename, 'w')
	f.write("+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+\n")
	if currentsub.selftext is not None and currentsub.selftext is not '':
		f.write(currentsub.selftext + "\n")
	else:
		f.write(currentsub.url + "\n")
	f.write("+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+\n")
	show_comment_id = False
	printComments(lambda x: f.write(x + "\n"), reddit.getComments(currentsub.permalink), 0)
	show_comment_id = True
	f.close()
	print("Content saved to " + filename)
	
def login(login):
	if len(login) == 0:
		print("No username given.")
		return
	spaceIndex = login.find(' ')
	username = login[0: spaceIndex]
	if spaceIndex > -1:
		password = login[spaceIndex + 1:]
	else:
		password = getpass.getpass()
	reddit.login(username, password)
	try:
		reddit.getLoggedInUser()
	except KeyError:
		print("Login failed!")
		return
	print("Login successful")
	
def self():
	try:
		user = reddit.getLoggedInUser()
	except KeyError:
		print("No valid user is logged in")
		return
	print("Name: {0}".format(user.name))
	print("Has mail: {0}".format(user.has_mail))
	print("Link karma: {0}".format(user.link_karma))
	print("Comment karma: {0}".format(user.comment_karma))
	
def reply(input):
	spaceIndex = input.find(' ')
	if spaceIndex > -1:
		id = input[0: spaceIndex]
		content = input[spaceIndex + 1:]
	else:
		id = ''
		content = input
	reddit.postComment("t1_" + id, content)

command = input("> ")
while command != "exit":
    if command.startswith('article'):
        selectthread(command[8:])
    elif command.startswith('reddit'):
        listsub(command[7:])
    elif command.startswith('save'):
        savecomments(command[5:])
    elif command.startswith('login'):
        login(command[6:])
    elif command.startswith('self'):
        self()
    elif command.startswith('reply'):
        reply(command[6:])
    else:
        listhelp()
    command = input("> ")